package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.common.constants.ProductConstants;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.product.ProductLibrary;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.ProductLibraryBatchAddRequest;
import com.zbkj.common.request.ProductLibraryRequest;
import com.zbkj.common.request.ProductLibrarySearchRequest;
import com.zbkj.common.response.*;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.service.dao.ProductLibraryDao;
import com.zbkj.service.service.ProductLibraryService;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author dazongzi
* @description ProductLibraryServiceImpl 接口实现
* @date 2025-06-05
*/
@Service
public class ProductLibraryServiceImpl extends ServiceImpl<ProductLibraryDao, ProductLibrary> implements ProductLibraryService {

    @Resource
    private ProductLibraryDao dao;

    /**
     * 加入产品库
     * @param request 添加参数
     * @return Boolean
     */
    @Override
    public ProductLibraryIdResponse add(ProductLibraryRequest request) {
        checkExists(request);
        ProductLibrary productLibrary = new ProductLibrary();
        BeanUtils.copyProperties(request, productLibrary);
        productLibrary.setId(null);
        productLibrary.setBrandId(BrandUtil.getBrandIdByUrl());
        boolean save = save(productLibrary);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加商品库失败");
        }
        ProductLibraryIdResponse response = new ProductLibraryIdResponse();
        response.setId(productLibrary.getId());
        return response;
    }

    @Override
    public List<ProductLibrary> getAdminListBrand(ProductLibrarySearchRequest request) {
        LambdaQueryWrapper<ProductLibrary> lqw = Wrappers.lambdaQuery();
        lqw.select(ProductLibrary::getLinkId);
        if (ObjectUtil.isNotNull(request.getType())) {
            lqw.eq(ProductLibrary::getType, request.getType());
        }
        lqw.eq(ProductLibrary::getBrandId, BrandUtil.getBrandIdByUrl());
        return dao.selectList(lqw);
    }

    @Override
    public List<ProductLibrarySelectedCategoryResponse> getSelectedCategoryList(ProductLibrarySearchRequest request, PageParamRequest pageParamRequest) {
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("type", ProductConstants.PRODUCT_LIBRARY_TYPE_CATEGORY);
        searchMap.put("brandId", BrandUtil.getBrandIdByUrl());
        return dao.findSelectedCategoryList(searchMap);
    }

    @Override
    public List<ProductLibrarySelectedMerchantResponse> getSelectedMerchantList(ProductLibrarySearchRequest request, PageParamRequest pageParamRequest) {
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("type", ProductConstants.PRODUCT_LIBRARY_TYPE_MERCHANT);
        searchMap.put("brandId", BrandUtil.getBrandIdByUrl());
        return dao.findSelectedMerchantList(searchMap);
    }

    @Override
    public List<ProductLibrarySelectedProductResponse> getSelectedProductList(ProductLibrarySearchRequest request, PageParamRequest pageParamRequest) {
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("type", ProductConstants.PRODUCT_LIBRARY_TYPE_PRODUCT);
        searchMap.put("brandId", BrandUtil.getBrandIdByUrl());
        return dao.findSelectedProductList(searchMap);
    }

    @Override
    public List<ProductLibrarySelectedBrandResponse> getSelectedBrandList(ProductLibrarySearchRequest request, PageParamRequest pageParamRequest) {
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("type", ProductConstants.PRODUCT_LIBRARY_TYPE_BRAND);
        searchMap.put("brandId", BrandUtil.getBrandIdByUrl());
        return dao.findSelectedBrandList(searchMap);
    }

    @Override
    public List<Integer> getAllSelectedList(ProductLibrarySearchRequest request, PageParamRequest pageParamRequest) {
        LambdaQueryWrapper<ProductLibrary> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductLibrary::getType, request.getType());
        List<ProductLibrary> list = list(wrapper);
        if (CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list.stream().map(ProductLibrary::getLinkId).distinct().collect(Collectors.toList());
    }

    @Override
    public boolean batchAdd(ProductLibraryBatchAddRequest request) {
        // 先删除同类型的其他商品库
        if (ObjectUtil.isNull(request.getLinkBrandId())) {
            request.setLinkBrandId(0);
        }
        deleteByType(request.getType(), request.getLinkBrandId());
        if (CollUtil.isEmpty(request.getLinkIds())) {
            return true;
        }
        // 去重
        request.setLinkIds(CollUtil.distinct(request.getLinkIds()));
        List<ProductLibrary> list = new ArrayList<>();
        for (Integer linkId : request.getLinkIds()) {
            checkExists(linkId, request.getType());
            ProductLibrary productLibrary = new ProductLibrary();
            productLibrary.setType(request.getType());
            productLibrary.setLinkId(linkId);
            productLibrary.setLinkBrandId(request.getLinkBrandId());
            productLibrary.setId(null);
            productLibrary.setBrandId(BrandUtil.getBrandIdByUrl());
            list.add(productLibrary);
        }
        boolean save = saveBatch(list);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加商品库失败");
        }
        return true;
    }

    private void deleteByType(Integer type, Integer linkBrandId) {
        remove(Wrappers.<ProductLibrary>lambdaQuery().eq(ProductLibrary::getType, type)
                .eq(ProductLibrary::getLinkBrandId, linkBrandId));
    }

    private void checkExists(Integer linkId, Integer type) {
        LambdaQueryWrapper<ProductLibrary> lqw = Wrappers.lambdaQuery();
        lqw.eq(ProductLibrary::getType, type);
        lqw.eq(ProductLibrary::getLinkId, linkId);
        lqw.last(" limit 1");
        Integer num = dao.selectCount(lqw);
        if (ObjectUtil.isNotNull(num) && num > 0) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "该数据不能重复添加到商品库");
        }
    }

    private void checkExists(ProductLibraryRequest request) {
        LambdaQueryWrapper<ProductLibrary> lqw = Wrappers.lambdaQuery();
        lqw.select(ProductLibrary::getId);
        lqw.eq(ProductLibrary::getType, request.getType());
        lqw.eq(ProductLibrary::getLinkId, request.getLinkId());
        lqw.last(" limit 1");
        Integer num = dao.selectCount(lqw);
        if (ObjectUtil.isNotNull(num) && num > 0) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "不能重复添加到商品库");
        }
    }

}

